'use strict';

// goog.provide('nuoding.hardware.Message');
var nuoding = {
    hardware: {
        Message: {}
    }
};
// goog.require('goog.crypt.base64');
nuoding.hardware.Message.START_FLAG = "nUoDiNg";
nuoding.hardware.Message.START_FLAG_LENGTH = nuoding.hardware.Message.START_FLAG.length;
/*
	将事件转换为硬件通信格式
	返回值：硬件消息字符串。不支持的消息则返回undefined。

	支持的消息格式：
	var send = stage.broadcast({
		type: "system",
		name: "keydown",
		value: evt
	});
    nUoDiNg5:12:17
	var send = stage.broadcast({
		type: "system",
		name: "keyup",
		value: evt
	});
    nUoDiNg5:22:17
        actor.stage.broadcast({
            type: "user",
            name: msg,
            value: data
        });
    nUoDiNg14:05:NameAValueB
*/
nuoding.hardware.Message.make = function (js_event) {
    var eventType = -1;
    var msg;
    if (js_event.type === "system") {
        if (js_event.name === "keydown") {
            eventType = 1;
            msg = "" + js_event.value.keyCode;
            msg = nuoding.hardware.Message.lengthInUtf8Bytes(msg) + ":" + msg;
        } else if (js_event.name === "keyup") {
            eventType = 2;
            msg = "" + js_event.value.keyCode;
            msg = nuoding.hardware.Message.lengthInUtf8Bytes(msg) + ":" + msg;
        }
    } else if (js_event.type === "user") {
        eventType = 0;
        msg = nuoding.hardware.Message.lengthInUtf8Bytes(js_event.name) + ":" + js_event.name;
        if (js_event.value != null && js_event.value != "" && !nullStr.test(js_event.value)) {
            //var value = JSON.parse(js_event.value);
            /*
            var typeofvalue = typeof(value);
            if (typeofvalue !== "object" && typeofvalue !== "function") {
                msg = msg + value;
            } else {
                msg = msg + js_event.value;
            }*/
            var obj_value = JSON.parse(js_event.value);
            var sendValue;
            if (obj_value.type === "string") {
                sendValue = obj_value.value;
            } else {
                sendValue = JSON.stringify(obj_value.value);
            }
            msg = msg + sendValue;
        }
    }
    if (eventType < 0) {
        return;
    }
    //msg = goog.crypt.base64.encodeString(msg);
    msg = eventType + msg;
    return nuoding.hardware.Message.START_FLAG + nuoding.hardware.Message.lengthInUtf8Bytes(msg) + ":" + msg + "\n";
};

/**
 * nUoDiNg长度:消息体
 * nUoDiNg31:04:name5:value13:targetActorId
 */
nuoding.hardware.Message.HardwareMsgPaser = function () {
    this.income = "";
};
nuoding.hardware.Message.HardwareMsgPaser.prototype.append = function (str) {
    this.income += str;
};
nuoding.hardware.Message.HardwareMsgPaser.prototype.nextMsg = function () {
    var headIndex = this.income.indexOf(nuoding.hardware.Message.START_FLAG);
    if (headIndex < 0) {
        return null;
    }
    var lengthEndIndex = this.income.indexOf(":", headIndex);
    if (lengthEndIndex < 0) {
        return null;
    }
    var lengthStartIndex = headIndex + nuoding.hardware.Message.START_FLAG_LENGTH;
    var str_length = this.income.substring(lengthStartIndex, lengthEndIndex);
    var length = parseInt(str_length) + /* for first ":" */ 1;
    if (this.income.length < lengthEndIndex + length) {
        return null;
    }
    var msgBodyStartIndex = lengthEndIndex + 1;
    var msgBody = this.income.substr(msgBodyStartIndex, length);
    //msgBody = goog.crypt.base64.decodeString(msgBody);
    var msg = nuoding.hardware.Message.parseBody(msgBody);
    this.income = this.income.substr(msgBodyStartIndex + length - 1);
    return msg;
};
/**
* 解析硬件消息为用户消息/调试信息
* 04:name5:value:13:targetActorId
	{
            type: "user",
            name: "name",
            value: "Value",
            targetActorId:'targetActorId'
     }
  04:name5:value0:
  {type: "user", name: "name", value: "value"}
  04:name0:0:
  {type: "user", name: "name", value: ""}

  14:debV
  {type:"system",name:"debug",value:"debV"}
*/
nuoding.hardware.Message.parseBody = function (str_msg) {
    var ch_type = str_msg.charAt(0);
    str_msg = str_msg.substring(1)
    switch (ch_type) {
        case '0': // user
            var evt = {
                type: "user"
            };
            var indexOfSp1 = str_msg.indexOf(":")
            var str_nameLength = str_msg.substring(0, indexOfSp1);
            var nameLength = parseInt(str_nameLength);
            evt.name = str_msg.substr(indexOfSp1 + 1, nameLength);
            var valueLengthStartIndex = indexOfSp1 + nameLength + 1;
            var valueLengthEndIndex = str_msg.indexOf(":", valueLengthStartIndex);
            var str_valueLength = str_msg.substring(valueLengthStartIndex, valueLengthEndIndex);
            var valueLength = parseInt(str_valueLength);
            evt.value = str_msg.substr(valueLengthEndIndex + 1, valueLength);
            var targetLengthStartIndex = valueLengthEndIndex + 1 + valueLength;
            var targetLengthEndIndex = str_msg.indexOf(":", targetLengthStartIndex);
            var str_targetLength = str_msg.substring(targetLengthStartIndex, targetLengthEndIndex);
            var targetLength = parseInt(str_targetLength);
            if (targetLength > 0) {
                evt.targetActorId = str_msg.substr(targetLengthEndIndex + 1, targetLength);
            }
            return evt;
            break;
        case '1': //debug
            var evt = {
                type: "system",
                name: "debug"
            };
            var indexOfSp1 = str_msg.indexOf(":")
            var str_nameLength = str_msg.substring(0, indexOfSp1);
            var nameLength = parseInt(str_nameLength);
            evt.value = str_msg.substr(indexOfSp1 + 1, nameLength);
            return evt;
        default:
            break;
    }
};

nuoding.hardware.Message.lengthInUtf8Bytes = function (str) {
    // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
    var m = encodeURIComponent(str).match(/%[89ABab]/g);
    return /*2 * */ (str.length + (m ? m.length : 0));
};